package com.ruoyi.web.zbAdmin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mongodb.client.result.UpdateResult;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.zbAdmin.controller.param.CaiZhaobiaoQuery;
import com.ruoyi.web.zbAdmin.domain.CaiZhaobiaoProperty;
import com.ruoyi.web.zbAdmin.mapper.CaiZhaobiaoPropertyMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 招标属性
 * @author liandyao
 * @date 2022/12/15 10:47
 */
@Api(tags="才能招标-招标详情属性")
@RestController
@RequestMapping("/zbApi/zhaobiaoProperty")
@Slf4j
public class CaiZhaobiaoPropertyController extends BaseController {

    @Autowired
    private CaiZhaobiaoPropertyMapper userMapper;

    public static final String collectionName = "cai_zhaobiao_property";

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户列表
     */
    @ApiOperation("获取招标详情属性列表")
    @GetMapping("/list")
    public TableDataInfo list(CaiZhaobiaoQuery userQuery) {

        log.info("=====>"+JSONUtil.toJsonStr(userQuery));
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();

        Query query = new Query();
//        if(StrUtil.isNotBlank(userQuery.getPhone())){
//            query.addCriteria(Criteria.where("phone").is(userQuery.getPhone()));
//        }
        if(StrUtil.isNotBlank(userQuery.getProvinceName())){
            query.addCriteria(Criteria.where("provinceName").is(userQuery.getProvinceName()));
        }

        if(StrUtil.isNotBlank(userQuery.getCityName())){
            query.addCriteria(Criteria.where("cityName").is(userQuery.getCityName()));
        }

        //招标类型查询
        if(StrUtil.isNotBlank(userQuery.getType())){
            query.addCriteria(Criteria.where("type").is(userQuery.getType()));
        }


        Criteria criteria = new Criteria();

        if(userQuery.getStartDate()!=null){
            criteria.andOperator(Criteria.where("createTime").gte(userQuery.getStartDate()),Criteria.where("createTime").lte(userQuery.getEndDate()));
        }

        query.addCriteria(criteria);

        //修改标记
        if(StrUtil.isNotBlank(userQuery.getUpdateFlag())){
            query.addCriteria(Criteria.where("updateFlag").is(userQuery.getUpdateFlag()));
        }

        //标题查询
        if(StrUtil.isNotBlank(userQuery.getNoticeTitle())){
            Pattern pattern = Pattern.compile("^.*" + userQuery.getNoticeTitle() + ".*$", Pattern.CASE_INSENSITIVE);

            query.addCriteria(Criteria.where("noticeTitle").regex(pattern));
        }


        // 设置起始页和每页查询条数
        Pageable pageable = PageRequest.of(userQuery.getCurPage(), userQuery.getPageSize(), Sort.by(Sort.Order.desc("createTime")));
        // 查询记录总数
        long totalCount = mongoTemplate.count(query,collectionName);
        //查询分页后的记录
        List<CaiZhaobiaoProperty> result = mongoTemplate.find(query.with(pageable), CaiZhaobiaoProperty.class, collectionName);

        return TableDataInfo.success(result,totalCount);
    }




    @ApiOperation("获取招标详情属性详细")
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable String id) {
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        CaiZhaobiaoProperty user = mongoTemplate.findById(id,CaiZhaobiaoProperty.class,collectionName);
        if(user==null){
            return AjaxResult.error("不存在!");
        }
        return AjaxResult.success("成功",user);
    }


    @ApiOperation("更新招标详情属性")
    @PostMapping("/update")
    public AjaxResult update(CaiZhaobiaoProperty user, HttpServletRequest request) {
        String _id = request.getParameter("_id");
        user.set_id(_id);
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        log.info("===>"+ JSONUtil.toJsonStr(user));
        if (StringUtils.isNull(user) || StringUtils.isNull(user.get_id())) {
            return AjaxResult.success("ID为空");
        }
        user.setUpdateFlag("1");
        user.setUpdateTime(DateUtil.now());
        user.setOperation((user.getOperation()==null?"":user.getOperation())+getUsername()+DateUtil.now()+"-修改! ");



        Document doc = new Document();
        //字段中会加上_class,该方法是为了去掉_class
        MappingMongoConverter mappingConverter =  (MappingMongoConverter)mongoTemplate.getConverter();
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        mongoTemplate.getConverter().write(user, doc);
        Update update = Update.fromDocument(doc);

        UpdateResult re = this.userMapper.getMongoTemplate().upsert(Query.query(Criteria.where("_id").is(user.get_id())),update,collectionName);


        //为了让修改的排序在前面,将cai_zhaobiao的createTime时间修改为当前时间,按照createTime逆序排序就会显示在前面
        Update updateZhaobiao = Update.update("createTime",DateUtil.now());
        this.userMapper.getMongoTemplate().upsert(Query.query(Criteria.where("id").is(_id)),updateZhaobiao,"cai_zhaobiao");

        return AjaxResult.success("修改成功",re.getMatchedCount());


    }

    @ApiOperation("删除招标详情属性信息")
    @PostMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable String id) {

        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        /**
         * 删除这条招标相关的所有信息
         */
        Update propertyTable = Update.update("delFlag", CaiZhaobiaoProperty.IS_DEL_YES).set("operation", getUsername() +DateUtil.now()+ "-删除").set("updateTime", DateUtil.now());
        UpdateResult result=mongoTemplate.upsert(Query.query(Criteria.where("_id").is(id)), propertyTable,collectionName);
        mongoTemplate.upsert(Query.query(Criteria.where("busId").is(id)), Update.update("delFlag",CaiZhaobiaoProperty.IS_DEL_YES),"cai_zhaobiao_detail");
        mongoTemplate.upsert(Query.query(Criteria.where("id").is(id)), Update.update("delFlag",CaiZhaobiaoProperty.IS_DEL_YES),"cai_zhaobiao");

        return AjaxResult.success("删除成功",result.getMatchedCount());

    }

    @ApiOperation("根据id查询招标详情-招标正文信息")
    @PostMapping("/findZhaobiaoById/{id}")
    public AjaxResult findZhaobiaoById(@PathVariable String id){

        JSONObject one = this.userMapper.getMongoTemplate().findOne(Query.query(Criteria.where("busId").is(id)), JSONObject.class, "cai_zhaobiao_detail");
        return AjaxResult.success("成功",one);
    }


    @ApiOperation("根据id查询招标信息")
    @PostMapping("/findZbById/{id}")
    public AjaxResult findZbById(@PathVariable String id){

        JSONObject one = this.userMapper.getMongoTemplate().findOne(Query.query(Criteria.where("id").is(id)), JSONObject.class, "cai_zhaobiao");
        return AjaxResult.success("成功",one);
    }
}
